<template>
	<div class="add-refinery-page">
		<t-card :bordered="false" class="refinery-card">
			<h2 class="page-title">{{ isEdit ? '编辑炼厂' : '新建炼厂' }}</h2>

			<div class="form-item">
				<div class="form-label">名称：</div>
				<t-input v-model="formData.refineryName" placeholder="请输入炼厂名称" class="form-input" />
			</div>

			<div class="form-item">
				<div class="form-label">地址：</div>
				<t-input v-model="formData.address" placeholder="请输入炼厂地址" class="form-input" />
			</div>

			<div class="form-item">
				<div class="form-label">城市：</div>
				<t-input v-model="formData.city" placeholder="请输入炼厂城市" class="form-input" />
			</div>

			<div class="form-item">
				<div class="form-label">省份：</div>

				<t-select @change='clickHandler' v-model="formData.provinceId">
					<t-option :key="item.id" :label="item.provinceName" :value="item.id" v-for="item in provinceList" />
				</t-select>
			</div>


			<div class="form-divider"></div>

			<div class="oil-types-container">
				<div class="oil-types-row">
					<t-checkbox v-for="(oilItem, index) in checkList" :key="oilItem.id"
						v-model:checked="checkList[index].status">
						{{ oilItem.name }}
					</t-checkbox>
				</div>
			</div>

			<div class="form-divider"></div>

			<!-- 根据勾选的油品类型显示对应的库存输入框 -->
			<div class="stock-inputs">
				<div v-for="oilItem in checkList" :key="oilItem.id" v-show="oilItem.status" class="form-item">
					<div class="form-label">{{ oilItem.name }}库存数量：</div>
					<t-input v-model="oilItem.stock" :placeholder="`请输入${oilItem.name}库存数量`" class="form-input" />
				</div>
			</div>

			<div class="form-footer">
				<t-button @click="onCancel" class="cancel-btn">取消</t-button>
				<t-button theme="primary" @click="onSubmit">确定</t-button>
			</div>
		</t-card>
	</div>
</template>

<script setup lang="ts">
	import { MessagePlugin } from 'tdesign-vue-next';
	import { ref, reactive, watch, onMounted } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import { getTjylOilTypeList, getProvinceList } from '@/api/common';
	import { addRefinery, editRefinery, addRefineryOilType, getRefineryDataById } from '@/api/refinery.ts'
	const route = useRoute();
	const router = useRouter();
	const isEdit = ref(false);

	// 定义油品类型接口
	interface OilType {
		id : string;
		name : string;
		status : boolean;
		[key : string] : any;
	}

	const checkList = ref<any[]>([]);



	interface StockMap {
		[key : string] : string;

	}

	interface FormData {
		id : string;
		refineryName : string;
		address : string;
		city : string;
		provinceId : string;
		provinceName : string;
		oilTypes : any;
		stockMap : StockMap[];
	}

	// 表单数据
	const formData = reactive<FormData>({
		id: '',
		refineryName: '',
		city: '',
		provinceName: '',
		provinceId: '',
		address: '',
		oilTypes: {
			'92#': false,
			'95#': false,
			'98#': false,
			'92#E': false,
			'95#E': false,
			'-0#': false,
			'-10#': false,
			'-20#': false,
			'-35#E': false
		},
		stockMap: []
	});

	const clickHandler = (data) => {
		formData.provinceId = data
		let res = provinceList.value.filter(item => {
			return item.id == data
		})
		formData.provinceName = res[0].provinceName
	};

	const getoilTypeList = async () => {
		const res = await getTjylOilTypeList({ pageSize: 999, pageNum: 1 })
		checkList.value = res.records.map((item : any) => {
			return {
				...item,
				status: false,
				stock: undefined

			}
		})
		console.log(checkList.value);
	}
	const provinceList = ref([])
	const getProvinceListApi = async () => {
		const res = await getProvinceList({ pageSize: 999, pageNum: 1 })
		provinceList.value = res.records.filter((item : any) => {
			return item.id != 0
		})

	}

	// 初始化页面
	onMounted(() => {
		// 检查是否是编辑模式
		const id = route.query.id;
		getoilTypeList();
		getProvinceListApi()
		if (id) {
			isEdit.value = true;
			getRefineryDataByIdApi(id)
			// 这里应该调用API获取炼厂详情
			// 暂时使用模拟数据
		}
	});

	const getRefineryDataByIdApi = (id) => {
		getRefineryDataById({
			id: id
		}).then(res => {
			fillFormData(res);
		})
	}

	// 表单校验
	const validateForm = () => {
		if (!formData.refineryName.trim()) {
			alert('请输入炼厂名称');
			return false;
		}

		if (!formData.address.trim()) {
			alert('请输入炼厂地址');
			return false;
		}

		// 检查是否至少选择了一种油品类型
		const hasSelectedOilType = checkList.value.some(item => item.status);
		if (!hasSelectedOilType) {
			alert('请至少选择一种油品类型');
			return false;
		}

		// 检查选中的油品类型是否都填写了库存
		for (const item of checkList.value) {
			if (item.status) {
				if (checkList.value.status && !checkList.value.stock) {
					alert(`请输入${item.name}库存数量`);
					return false;
				}
			}
		}

		return true;
	};

	// 监听油品类型变化，确保stockMap中有所有选中类型的键
	// watch(
	//   checkList,
	//   (newList) => {
	//     // 处理新增的类型
	//     for (const item of newList) {
	//       if (item.status) {
	//         formData.stockMap.push({
	//           id: item.id,
	//           num: ''
	//         })
	//       }
	//     }
	//   },
	// );

	// 填充表单数据
	const fillFormData = (data : any) => {
		formData.id = data.id || '';
		formData.refineryName = data.refineryName || '';
		formData.address = data.address || data.province || '';
		formData.city = data.city || '';
		formData.provinceId = data.provinceId || '';
		formData.provinceName = data.provinceName || '';

		// 重置油品类型
		for (const key in formData.oilTypes) {
			formData.oilTypes[key] = false;
		}

		// 如果有油品类型数据，则设置选中
		if (data.oilTypes && Array.isArray(data.oilTypes)) {
			data.oilTypes.forEach((type : string) => {
				if (type in formData.oilTypes) {
					formData.oilTypes[type] = true;
				}
			});
		} else if (data.currentOil) {
			const currentOil = data.currentOil as string;
			if (currentOil in formData.oilTypes) {
				formData.oilTypes[currentOil] = true;
			}
		}

		// 清空之前的库存映射
		formData.stockMap = [];

		// 设置库存数据
		if (data.stocks) {
			Object.assign(formData.stockMap, data.stocks);
		} else if (data.currentOil && data.totalStock) {
			const currentOil = data.currentOil as string;
			formData.stockMap[currentOil] = (data.totalStock as string).replace('KG', '').trim();
		}
	};

	// 取消按钮点击
	const onCancel = () => {
		router.back();
	};

	// 提交表单
	const onSubmit = () => {
		if (validateForm()) {
			// 将数据整理为提交格式
			const stocks = checkList.value.filter(item => {
				return item.status === true && item.stock;
			}).map(item => {
				return {
					id: item.id,
					num: item.stock,
					name:item.name
				}
			})
			const selectedOilTypes = Object.entries(formData.oilTypes)
				.filter(([_, selected]) => selected)
				.map(([type]) => type);

			const submitData = {
				refineryName: formData.refineryName,
				city: formData.city,
				provinceId: formData.provinceId,
				province: formData.provinceName,
				address: formData.address,
				oilTypes: selectedOilTypes,
				stocks: stocks,
				id:formData.id
				
			};
			// 只提交选中油品类型的库存
			for (const type of selectedOilTypes) {
				submitData.stocks[type] = formData.stockMap[type];
			}

			// 这里应该调用API保存数据
			if(isEdit.value){
				editRefinery(submitData).then(res => {
					MessagePlugin.success('编辑成功')
					setTimeout(() => {
						// 保存成功后返回列表页
						router.push('/refinery/management');
					}, 1000)
				})
			}else{
				addRefinery(submitData).then(res => {
					MessagePlugin.success('添加成功')
					setTimeout(() => {
						// 保存成功后返回列表页
						router.push('/refinery/management');
					}, 1000)
				})
			}
			
		}
	};
</script>

<style lang="less" scoped>
	.add-refinery-page {
		padding: 20px;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.refinery-card {
		max-width: 1000px;
		margin: 0 auto;
		padding: 24px;

		.page-title {
			font-size: 20px;
			font-weight: bold;
			margin-bottom: 30px;
			color: #333;
		}

		.form-item {
			display: flex;
			margin-bottom: 20px;
			align-items: center;
		}

		.form-label {
			width: 120px;
			flex-shrink: 0;
			color: #666;
		}

		.form-input {
			flex: 1;
			max-width: 480px;
		}

		.form-divider {
			height: 1px;
			background-color: #eee;
			margin: 24px 0;
		}

		.oil-types-container {
			padding: 8px 0;
		}

		.oil-types-row {
			display: flex;
			margin-bottom: 16px;
			flex-wrap: wrap;

			:deep(.t-checkbox) {
				margin-right: 40px;
				margin-bottom: 8px;
			}
		}

		.stock-inputs {
			margin-top: 16px;
		}

		.form-footer {
			display: flex;
			justify-content: flex-end;
			margin-top: 40px;

			.t-button {
				min-width: 80px;
			}

			.cancel-btn {
				margin-right: 16px;
			}
		}
	}
</style>